package cn.sc.summer.core.filter;

import cn.hutool.extra.spring.SpringUtil;
import cn.sc.summer.core.wrapper.DecryptRequestWrapper;
import cn.sc.summer.exception.hodler.SpringContextHolder;
import cn.sc.summer.token.service.EncryptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 类名：接口解密过滤器
 *
 * @author a-xin
 * @date 2024/5/13 09:52
 */
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class DecryptFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        SpringContextHolder.setHttpServletRequest(request);

        EncryptService encryptService = SpringUtil.getBean(EncryptService.class);
        if (!encryptService.checkDecrypt(request)){
            filterChain.doFilter(servletRequest, servletResponse);
            return;
        }

        DecryptRequestWrapper decryptRequestWrapper = new DecryptRequestWrapper(request, encryptService);
        filterChain.doFilter(decryptRequestWrapper, servletResponse);

    }

}
